package com.gem.day15;

/**
 * 本类用来演示Java死锁
 * 
 * 死锁是指多线程之间相互持有对方锁标记,
 * 死锁在开发中必须编码谨慎来避免,一旦出现,程序无法继续!
 * 
 * @author easonsy
 * 2020年8月10日 下午2:31:49
 */
public class DeadLock {

	Object o1 = new Object();
	Object o2 = new Object();

	public static void main(String[] args) {

		Thread t1 = new Thread1();
		Thread t2 = new Thread2();
		t1.start();
		t2.start();

		//哲学家就餐问题
		/*//匿名线程
		new Thread(new Runnable() {
			@Override
			public void run() {
				//中国人拿到了刀叉
				synchronized ("刀叉") {
					System.out.println(Thread.currentThread().getName() + ": 你不给我筷子,我就不给你刀叉.");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized ("筷子") {
						System.out.println(Thread.currentThread().getName() + ": 给你刀叉.");
					}
				}
			}
		}, "中国人").start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				//英国人拿到了筷子
				synchronized ("筷子") {
					System.out.println(Thread.currentThread().getName() + ": 你先给我刀叉,我再给你筷子.");
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized ("刀叉") {
						System.out.println(Thread.currentThread().getName() + ": 好吧,筷子给你了.");
					}
				}
			}
		}, "英国人").start();*/
	}
}

class Thread1 extends Thread {
	@Override
	public void run() {
		synchronized (new DeadLock().o1) {
			System.out.println(1);
			synchronized (new DeadLock().o2) {
				System.out.println(2);
			}
		}
	}
}

class Thread2 extends Thread {
	@Override
	public void run() {
		synchronized (new DeadLock().o2) {
			System.out.println(3);
			synchronized (new DeadLock().o1) {
				System.out.println(4);
			}
		}
	}
}
